package com.android.antelopeapp.activity;

import android.content.Context;
import android.content.Intent;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v7.app.ActionBarActivity;
import android.support.v7.widget.Toolbar;
import android.util.Log;
import android.view.View;
import android.view.ViewConfiguration;
import android.widget.TextView;
import android.widget.Toast;

import com.alibaba.sdk.android.AlibabaSDK;
import com.alibaba.sdk.android.login.LoginService;
import com.alibaba.sdk.android.trade.ItemService;
import com.android.antelopeapp.R;
import com.android.antelopeapp.constant.MsgConfig;
import com.taobao.tae.sdk.TaeSDK;
import com.taobao.tae.sdk.callback.CallbackContext;
import com.taobao.tae.sdk.callback.LoginCallback;
import com.taobao.tae.sdk.callback.TradeProcessCallback;
import com.taobao.tae.sdk.constant.ResultCode;
import com.taobao.tae.sdk.model.Session;
import com.taobao.tae.sdk.model.TradeResult;
import com.taobao.tae.sdk.webview.TaeWebViewUiSettings;
import com.umeng.analytics.MobclickAgent;

import java.lang.reflect.Field;

/**
 * 基础类，封装Activity常用的方法
 * */

public abstract class BaseActivity extends ActionBarActivity {
    public static final String TAG = "BaseActivity";
	/**
	 * Toolbar 相当于 actionbar
	 * */
    protected Toolbar mToolbar;
    protected Handler mHandler;

    public static int MSG_TOAST;
    public static String MSG_TOAST_DATA="data";
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(getLayoutResource());
        mToolbar = (Toolbar) findViewById(R.id.toolbar);
        if (mToolbar != null) {
            setSupportActionBar(mToolbar);
//            mToolbar.setNavigationIcon(R.drawable.mylogo);
            //todo logo
//            mToolbar.setLogo(R.drawable.mylogo);
        }
        /**通用消息处理*/
        mHandler = new Handler(new Handler.Callback() {
            @Override
            public boolean handleMessage(Message msg) {
                if(msg.what == MSG_TOAST){
                    toast(msg.getData().getString(MSG_TOAST_DATA));
                }
                return true;
            }
        });
    }

    /**友盟组件*/
    public void onResume() {
        super.onResume();
        MobclickAgent.onResume(this);
    }
    public void onPause() {
        super.onPause();
        MobclickAgent.onPause(this);
    }

    protected abstract int getLayoutResource();

    protected void setActionBarIcon(int iconRes) {
        mToolbar.setNavigationIcon(iconRes);
    }

    /**
     * 使得overflow按钮一直显示在actionbar上
     * */
    protected void setOverflowShowingAlways() {
        /* todo 暂时禁用
        try {
            ViewConfiguration config = ViewConfiguration.get(this);
            Field menuKeyField = ViewConfiguration.class.getDeclaredField("sHasPermanentMenuKey");
            menuKeyField.setAccessible(true);
            menuKeyField.setBoolean(config, false);
        } catch (Exception e) {
            e.printStackTrace();
        }
        */
    }

    /**
     * 为了使得阿里百川的logincallback生效，必须重写此函数
     * */
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        CallbackContext.onActivityResult(requestCode, resultCode, data);
    }

    /**
     * 显示淘宝登录界面
     * */
    public void showLogin(View view) {
        //登录服务
        LoginService loginService = AlibabaSDK.getService(LoginService.class);
        if(loginService.getSession().isLogin()){
            toast(loginService.getSession().getUser()+"您已登录");
        }else {
            loginService.showLogin(BaseActivity.this, new LoginCallback() {

                @Override
                public void onSuccess(Session session) {
                    Toast.makeText(BaseActivity.this, "欢迎" + session.getUser().nick,
                            Toast.LENGTH_SHORT).show();
                }

                @Override
                public void onFailure(int code, String message) {
                    Toast.makeText(BaseActivity.this, "授权取消 code:"+code+" msg:"+message,
                            Toast.LENGTH_SHORT).show();
                }
            });
        }
    }


    /**
     * Tae唤起商品组件
     * */
    public void showItemDetail(String title,String uid,int type) {
        Log.v(TAG,"showItemDetail uid="+uid+" type="+type);
        //商品详情服务
        ItemService service = AlibabaSDK.getService(ItemService.class);
        TaeWebViewUiSettings taeWebViewUiSettings = new TaeWebViewUiSettings();
        taeWebViewUiSettings.title=title;
        service.showItemDetailByOpenItemId(this, new com.alibaba.sdk.android.trade.callback.TradeProcessCallback() {
            @Override
            public void onPaySuccess(com.alibaba.sdk.android.trade.model.TradeResult tradeResult) {
                Toast.makeText(BaseActivity.this, "支付成功", Toast.LENGTH_SHORT).show();
            }

            @Override
            public void onFailure(int code, String msg) {
                Log.v("Tae", "showItem onFailure code:" + code + " msg:" + msg);
                if (code == ResultCode.SYSTEM_EXCEPTION.code) {
                    Toast.makeText(BaseActivity.this, "系统异常",
                            Toast.LENGTH_SHORT).show();
                } else if (code == ResultCode.QUERY_ORDER_RESULT_EXCEPTION.code) {
                    Toast.makeText(BaseActivity.this, "确认交易订单失败",
                            Toast.LENGTH_SHORT).show();
                }
            }
        }, taeWebViewUiSettings, uid, type, null);
    }

    public void showItemDetail(String title,String uid,String type){
        Log.v(TAG,"showItemDetail uid="+uid+" type="+type);
        int iType = 0 ;
        if(type.equals("淘宝")){
            iType = 1;
        }else if(type.equals("天猫")){
            iType = 2;
        }
        showItemDetail(title,uid,iType);
    }

    /**
     * 展示一个特定颜色的Toast
     *
     * @param message 抛送的消息
     */
    protected void toast(String message) {
        View toastRoot = getLayoutInflater().inflate(R.layout.toast, null);
        Toast toast = new Toast(getApplicationContext());
        toast.setView(toastRoot);
        TextView tv = (TextView) toastRoot.findViewById(R.id.toast_notice);
        tv.setText(message);
        toast.show();
    }
    /**
     * 展示一个特定颜色的Toast
     *
     * @param message 抛送的消息
     */
    protected void toast(int message) {
        View toastRoot = getLayoutInflater().inflate(R.layout.toast, null);
        Toast toast = new Toast(getApplicationContext());
        toast.setView(toastRoot);
        TextView tv = (TextView) toastRoot.findViewById(R.id.toast_notice);
        tv.setText(message);
        toast.show();
    }

    public Handler getmHandler(){
        return mHandler;
    }

    public void sendToastMsg(String msgString){
        Message msg = new Message();
        Bundle data = new Bundle();
        data.putString(BaseActivity.MSG_TOAST_DATA, msgString);
        msg.setData(data);
        mHandler.sendMessage(msg);
    }


}